import { Outlet } from "react-router-dom";
import { useEffect, useState, useRef } from "react";
import * as api from "../../../api/Commoditymodule";
import {
  Avatar,
  Button,
  Checkbox,
  Form,
  Image,
  Input,
  Table,
  Tooltip,
  Upload,
} from "antd";
import { ColumnsType } from "antd/es/table";
import {
  ContainerOutlined,
  DeleteRowOutlined,
  SearchOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { ModalCom } from "../../../componement/modal";
import { UploadCom } from "../../../componement/Upload";
import PubSub from "pubsub-js";
import { message, Space } from "antd";

export const ProductListCom = () => {
  //message的参数

  let [rowList, setRowList] = useState<any>();
  //modal参数
  const [open, setOpen] = useState(false);
  let [title, settitle] = useState("增加");

  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  let [list, setList] = useState([]);
  let [url, setUrl] = useState<any>("");

  let bb = useRef<any>(null);
  // let [imageUrl, setImageUrl] = useState("");

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  //表单校验之后的逻辑
  let onFinish = async (values: any) => {
    console.log(title);
    console.log(values);
    if (title === "增加") {
      if (!bb.current.imageUrl) {
        message.error("请添加图片");
        return;
      } else {
        try {
          let a = { ...values, imageUrl: bb.current.imageUrl };
          console.log(a);
          let res = await api.addItem(a);
          console.log(res);
          getList();
          messageApi.success({
            type: "success",
            content: "添加成功",
          });
        } catch (error) {
          messageApi.error({
            type: "error",
            content: "添加失败",
          });
          console.log(error);
        }
        setUrl("");
        bb.current.imageUrl = "";
        form.resetFields();
        setOpen(false);
      }
    } else {
      try {
        let res = await api.editItem({
          ...values,
          product_id: rowList!.product_id,
          imageUrl: bb.current.imageUrl
            ? bb.current.imageUrl
            : rowList!.imageUrl,
        });
        console.log(res);
        getList();
        messageApi.success({
          type: "success",
          content: "编辑成功",
        });
        // console.log(rowList);
      } catch (error) {
        messageApi.error({
          type: "error",
          content: "编辑失败",
        });
        console.log(error);
      }
      setUrl("");
      form.resetFields();
      setOpen(false);
    }
  };
  //封装获取数据的方法
  let getList = async () => {
    try {
      let res = await api.getGoods();
      console.log(res);
      let newList = res.data.data.map((p: any) => {
        return { ...p, key: p.product_id };
      });
      //   console.log(newList);
      setList(newList);
    } catch (error) {
      console.log(error);
    }
  };
  interface DataType {
    key?: React.Key;
    name?: string;
    age?: number;
    address?: string;
    product_id?: string;
  }
  //编辑数据
  let edit = (v: any) => {
    return () => {
      settitle("编辑");
      setUrl(v.imageUrl);
      console.log(v.imageUrl);
      setRowList(v);
      for (const key in v) {
        form.setFieldValue(key, v[key]);
      }

      setOpen(true);
    };
  };
  //展示数据
  let columns: ColumnsType<DataType> = [
    {
      title: "产品图片",
      dataIndex: "imageUrl",
      render: (imageUrl) => {
        return (
          <Avatar
            shape="square"
            src={imageUrl ? imageUrl : "https://joeschmoe.io/api/v1/random"}
            style={{ backgroundColor: "#87d068" }}
            icon={<UserOutlined />}
          />
        );
      },
    },
    {
      title: "vip描述",
      dataIndex: "description",
    },
    {
      title: "类目id",
      dataIndex: "category_id",
    },
    {
      title: "产品数量",
      dataIndex: "inventory",
    },
    {
      title: "产品描述",
      dataIndex: "productName",
    },
    {
      title: "操作",
      render: (i, v) => {
        return (
          <>
            <Tooltip title="禁用">
              <Button shape="circle" icon={<SearchOutlined />} />
            </Tooltip>
            <Tooltip title="编辑">
              <Button
                shape="circle"
                icon={<ContainerOutlined />}
                onClick={edit(v)}
              />
            </Tooltip>
            <Tooltip title="删除">
              <Button
                shape="circle"
                danger
                icon={<DeleteRowOutlined />}
                onClick={delItem(v.product_id)}
              />
            </Tooltip>
          </>
        );
      },
    },
  ];

  //删除
  let delItem = (id: any) => {
    return async () => {
      //   console.log(id);
      try {
        let res = await api.delhanlder(id);
        console.log(res);
        getList();
      } catch (error) {
        console.log(error);
      }
    };
  };

  //批量删除
  let batchDel = async () => {
    if (!selectedRowKeys.length) return;
    try {
      for (var i = 0; i < selectedRowKeys.length; i++) {
        let res = await api.delhanlder(selectedRowKeys[i]);
      }
      getList();
    } catch (error) {
      console.log(error);
    }
  };
  //增加
  let addItem = () => {
    settitle("增加");
    setOpen(true);
  };
  //点击modal onok
  let handleOk = () => {
    // settitle("增加")
    form.submit();
    console.log(bb);
  };

  // let [cc,setCC] = useState(3)
  //打开页面展示数据
  useEffect(() => {
    // setCC(9)
    // console.log(cc);
    // console.log(form);
    // console.log(name);
    getList();
  }, []);
// let selectedRowKeyskk = true
//   useEffect(() => {
//     console.log(11);
    
//     selectedRowKeyskk = selectedRowKeys.length? true : false
    
//   }, [selectedRowKeys.length]);
  const [messageApi, contextHolder] = message.useMessage();
  //点击modal取消的按钮
  const handleCancel = () => {
    setUrl(" ");
    form.resetFields();
    console.log("Clicked cancel button");
    setOpen(false);
  };

  return (
    <div>
      <div>{!Boolean(selectedRowKeys.length)}</div>
      {/* {cc} */}
      {contextHolder}
      <div className="operation-row">
        <Button onClick={addItem}>+增加</Button>
        
        <Button onClick={batchDel} disabled={!Boolean(selectedRowKeys.length)}>
          <span>批量删除</span>
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={list}
        scroll={{ y: 400 }}
        rowSelection={rowSelection}
      />
      <ModalCom
        open={open}
        title={title}
        handleOk={handleOk}
        handleCancel={handleCancel}
      >
        
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            // initialValue={bb.current?.imageUrl}
            label="产品图片"
            name="imageUrl"
            // rules={[{ required: true, message: "Please input your imageUrl!" }]}
          >
            <UploadCom
              rules={[
                { required: true, message: "Please input your imageUrl!" },
              ]}
              url={url}
              ref={bb}
              method="post"
              name="headimgurl"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={true}
              action="/api/students/uploadStuAvatar"
            ></UploadCom>
          </Form.Item>
          <Form.Item
            label="类目id"
            name="category_id"
            rules={[
              { required: true, message: "Please input your category_id!" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="	vip描述"
            name="description"
            rules={[
              { required: true, message: "Please input your description!" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="产品数量"
            name="inventory"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="产品描述"
            name="productName"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: "Please input your price!" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </ModalCom>
    </div> 
  );
};
